<?php

namespace App\Http\Controllers\TwoLevelMainte;

use App\Http\Controllers\Controller;
use App\Models\Bus\Bus;
use App\Models\TwoLevelMainte\TwoLevelMainte;
use App\Models\TwoLevelMainte\TwoLevelMainteBus;
use Illuminate\Database\Query\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TwoLevelMainteController extends Controller
{
    /**
     * 保险列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function twoLevelMainteList(Request $request)
    {
        $params = $request->all();
        $data = $this->getTwoLevelMainteList($params)->get()->groupBy('license_plate_num')->toArray();
        if ($data) {
            $data = $this->transData($data);
        }

        return response()->formatJson(['personnel' => $data,]);
    }

    public function getTwoLevelMainteList($params): Builder
    {
        $query = DB::table('akbus_two_level_mainte as two')
            ->join('akbus_two_level_mainte_bus as bus', 'two.id', '=', 'bus.two_mainte_id')
            ->select('two.id','two.type','two.date','bus.*' );

        if (isset($params['license_plate_num'])) {
            $query->where('bus.license_plate_num', 'like', '%'.$params['license_plate_num'].'%');
        }

        return $query;
    }

    public function transData($data)
    {
        $carType = ['燃气车', '纯电动'];
        $carBrand = ['东风牌', '亚星牌', '宇通牌', '中通牌'];
        $bus = Bus::query()->select(['license_plate_num', 'type', 'brand', 'engine_num', 'frame_nun'])->get();
        $columns = [
            'type_time_1' => '二级维护',
            'type_time_2' => '更换机油',
            'type_time_9' => '更换空滤',
            'type_time_3' => '更换齿轮油',
            'type_time_4' => '更换滤芯（高压）',
            'type_time_5' => '更换滤芯（低压）',
            'type_time_6' => '灭火器',
            'type_time_7' => '灭火弹',
            'type_time_8' => '防冻液',
        ];

        $result = [];
        foreach ($data as $key => $v) {
            $item = [];
            // 转化数据
            $item['license_plate_num'] = '陕G'.$key;
            $busData = $bus->where('license_plate_num', '陕G'.$key)->first();
            $item['bus_type'] =  $carType[$busData->type];
            $item['brand'] = $carBrand[$busData->brand];
            $item['frame_nun'] = $busData->frame_nun;
            $item['engine_num'] = $busData->engine_num;
            foreach ($v as $kk => $vv) {
                $index = array_search($vv['type'], $columns, true);
                $item[$index] = $vv['date'];
            }

            $result[] = $item;
        }

        return $result;
    }

    /**
     * 获取保险详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function twoLevelMainteInfo(Request $request)
    {
        $params = $request->all();
        $data = DB::table('akbus_two_level_mainte as two')
            ->join('akbus_two_level_mainte_bus as bus', 'two.id', '=', 'bus.two_mainte_id')
            ->where('bus.license_plate_num', str_replace('陕G', '', $params['license_plate_num']))
            ->get()
            ->groupBy('type')
            ->toArray();
        $carType = ['燃气车', '纯电动'];
        $carBrand = ['东风牌', '亚星牌', '宇通牌', '中通牌'];
        $busData = Bus::query()
            ->select(['id', 'license_plate_num', 'type', 'brand', 'engine_num', 'frame_nun'])
            ->where('license_plate_num', str_replace('陕G', '', $params['license_plate_num']))
            ->first();

        $result = [];
        $result['license_plate_num'] = $busData->id;
        $result['bus_type'] = $carType[$busData->type];
        $result['brand'] = $carBrand[$busData->brand];
        $result['frame_nun'] = $busData->frame_nun;
        $result['engine_num'] = $busData->engine_num;
        foreach ($data as $type => $v) {
            $result['type'][] = [
                'name' => $type,
                'date' => collect($v)->max('date')
            ];
        }

        return response()->formatJson(['result' => $result]);
    }

    /**
     * 添加保险
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function addTwoLevelMainte(Request $request)
    {
        $params = $request->all();
        if (isset($params['license_plate_num'])) {
            $params['bus_id'] = $params['license_plate_num'];
        }
        if ($params['type']) {
            // 转化时间
            foreach ($params['type'] as $k => $v) {
                $params['type'][$k]['time'] = date('Y-m-d', strtotime($v['time']));
            }
        }
        $params['type'] = json_encode($params['type']);
        $params['created_at'] = date('Y-m-d H:i:s');
        unset(
            $params['license_plate_num'],
            $params['bus_type'],
            $params['engine_num'],
            $params['frame_nun'],
            $params['brand']
        );
        $data = TwoLevelMainte::query()->insertGetId($params);
        $result = $data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑保险
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editTwoLevelMainte(Request $request)
    {
        $params = $request->all();
        if (isset($params['license_plate_num'])) {
            $params['bus_id'] = $params['license_plate_num'];
        }
        $id = $params['id'];
        if ($params['type']) {
            // 转化时间
            foreach ($params['type'] as $k => $v) {
                $params['type'][$k]['time'] = date('Y-m-d', strtotime($v['time']));
            }
        }
        $params['type'] = json_encode($params['type']);
        $params['updated_at'] = date('Y-m-d H:i:s');
        unset(
            $params['id'],
            $params['brand'],
            $params['bus_type'],
            $params['engine_num'],
            $params['frame_nun'],
            $params['license_plate_num']
        );
        $data = TwoLevelMainte::query()->where('id', $id)->update($params);
        $result = $data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 删除保险
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function delTwoLevelMainte(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            $delCount = TwoLevelMainte::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 创建车辆信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function store(Request $request)
    {
        $params = $request->all();
        $fixedCost = new TwoLevelMainte($params);
        $result = $fixedCost->save();
        $message = $result ? '添加成功' : '添加失败';

        if ((int) $params['object_type'] === 0) {
            $bus = Bus::query()->pluck('license_plate_num')->toArray();
        } elseif ((int) $params['object_type'] === 1) {
            $bus = Bus::query()->where('type', $params['bus_type'])->pluck('license_plate_num')->toArray();
        } elseif ((int) $params['object_type'] === 2) {
            $bus = Bus::query()->where('brand', $params['bus_brand'])->pluck('license_plate_num')->toArray();
        } else {
            $bus = explode(',', $params['depIds']);
        }

        $busInsert = [];
        foreach ($bus as $v) {
            $busInsert[] = ['license_plate_num' => str_replace('陕G', '', $v)];
        }

        if ($busInsert) {
            foreach ($busInsert as $v) {
                $fixedCostBus = new TwoLevelMainteBus($v);
                $fixedCost->bus()->save($fixedCostBus);
            }
        }

        return response()->formatJson($result, $message);
    }
}
